package com.dencycheng.singleton;

/**
 * @Author dencycheng
 * @Date 2019/12/15 20:21
 */
public class LazyDoubleCheckSingleton {

    /**
     * 线程安全的初始化（创建对象的重排序）
     * 防止3，2步骤颠倒出现的空指针异常
     * 当线程0是按照1，3，2的创建顺序时，正好执行到第三步，线程1介入。
     * 当线程1判断lazyDoubleCheckSingleton是有内存指向的，这时候直接返回会出现空指针异常
     * volatile 防止jvm在创建对象的时候发生重排序的问题
     */
    private volatile static LazyDoubleCheckSingleton lazyDoubleCheckSingleton;

    private LazyDoubleCheckSingleton() {

    }

    public synchronized static LazyDoubleCheckSingleton getInstance() {
        if (lazyDoubleCheckSingleton == null) {
            synchronized (LazyDoubleCheckSingleton.class) {
                if (lazyDoubleCheckSingleton == null) {
                    lazyDoubleCheckSingleton = new LazyDoubleCheckSingleton();
                    //1.分配内存
                    //2.初始化对象
                    //3.设置 lazyDoubleCheckSingleton 指向刚分派好的内存
                }
            }
        }
        return lazyDoubleCheckSingleton;
    }
}
